<script>
	import {
		getUserInfo,
		getProductCode
	} from './api/index.js';
	import WebSocketManager from './utils/websocket.js';
	import {
		useUserStore
	} from './store/index.js'
	import config from './config.js';
	// const userStore = useUserStore()
	export default {
		data() {
			return {
				timer: null,
				wsManager: null,
				userStore: useUserStore(),
				params: [],
				eventSource: null
			};
		},
		onLaunch: function() {
			console.log('App Launch')
		},
		onShow: function() {
			console.log('App Show')
		},
		onHide: function() {
			console.log('App Hide')
			// this.stopSSE();
		},
		watch: {
			'userStore.userInfo': {
				handler: function(newVal, oldVal) {
					// console.log(12);
					if (!newVal || !newVal.token) { // 当 userInfo 存在，但是 token 为空时执行
						// console.log(23);
						// this.stopSSE();
						if (this.timer) {
							clearInterval(this.timer);
							this.timer = null;
						}

					}
				},
				deep: true, // 深度监听
				immediate: true
			}
		},

		methods: {
			startSSE() {
				if (!this.eventSource) {
					this.eventSource = new EventSource(config.API_URL + '/cache/gethq');

					this.eventSource.onmessage = (event) => {
						const sseData = JSON.parse(decodeURIComponent(escape(window.atob(event.data))));
						// console.log('sseData',sseData);
						this.userStore.setSseData(sseData);
					};

					this.eventSource.onerror = (error) => {
						// console.error('SSE error:', error);
						// this.stopSSE(); // 出现错误时停止监听
					};
				}
			},
			stopSSE() {
				if (this.eventSource) {
					this.eventSource.close();
					this.eventSource = null; //先设置为null
					this.eventSource.onmessage = null; // 移除 message 监听
					this.eventSource.onerror = null; // 移除 error 监听
				}
			},
			// WebSocket 获取行情
			startWebSocket(params) {
				this.wsManager = new WebSocketManager('wss://api.huobi.pro/ws');
				// 连接并订阅数据
				this.wsManager.connect(params);
				// 设置消息回调
				this.wsManager.onMessage((data) => {
					// console.log('Received WebSocket data:', data);
					if (data && data.ch) {
						const list = this.userStore.getProsuctList();

						// 提取通道名
						const channelName = data.ch.split('.')[1];

						if (list.length > 0) {
							// 查找是否存在同名的项
							const existingItem = list.find(item => item.name === channelName);

							if (existingItem) {
								// 更新现有项
								existingItem.tick = data.tick;
								// 如果 list 不是响应式的，更新整个数组来强制触发更新
								this.userStore.setProsuctList([...list]);
							} else {
								// 添加新项
								list.push({
									name: channelName,
									tick: data.tick
								});
								// 如果 list 不是响应式的，更新整个数组来强制触发更新
								this.userStore.setProsuctList([...list]);
							}

						} else {
							// 初始化列表
							this.userStore.setProsuctList([{
								name: channelName,
								tick: data.tick
							}]);
						}

						if (this.userStore.getSelect().name && (channelName == this.userStore.getSelect().name)) {
							this.userStore.setSelect({
								name: channelName,
								tick: data.tick
							})
							// console.log('channelName ', channelName, data);
						}
					}
				});
			},
			stopWebSocket() {
				if (this.wsManager) {
					this.wsManager.close(this.params);
				}
			},
			getIndex() {
				this.timer = setInterval(() => {
					getUserInfo().then(res => {
						uni.setStorageSync('ISREALID', res.data.user_check_status)
						uni.setStorageSync('USERINDEX', res.data)
						// 广播更新事件
						uni.$emit('userInfoUpdated', res.data);
						this.userStore.setUserInfo(res.data);
					})
				}, 30 * 1000)
			}
		},
		mounted() {
			// 固定主题色
			const colorInfo = uni.getStorageSync('themeColor') ? JSON.parse(uni.getStorageSync('themeColor')) : ''
			if (colorInfo) {
				document.documentElement.style.setProperty('--theme-color', colorInfo.themeColor);
				document.documentElement.style.setProperty('--theme-text-color', colorInfo.themeTextColor);
				document.documentElement.style.setProperty('--theme-box-bg', colorInfo.themeBoxBg);
				document.documentElement.style.setProperty('--theme-input-bg', colorInfo.themeInputBg);
				// document.documentElement.style.setProperty('--theme-pupop-bg', colorInfo.themePupopBg);

			}
			this.startSSE();
			if (uni.getStorageSync('H5STOCK_USERINFO').token) {
				this.getIndex();
			}
			getProductCode().then(res => {
				if (res.code == 1) {
					const list = res.data
					list.forEach((item) => {
						this.params.push(`market.${item}.ticker`)
					})
					// this.startWebSocket(this.params)
				}
			})
		},
		beforeDestroy() {
			this.stopWebSocket()
			clearInterval(this.timer)
			this.timer = null
			this.stopSSE()
		},
		destroyed() {
			this.stopWebSocket()
			clearInterval(this.timer)
			this.timer = null
			this.stopSSE()
		}
	}
</script>

<style lang="scss">
	@import url('./static/fonts/iconfont.css');

	:root {
		--theme-color: #f6f7fb;
		/* 默认主题色 */
		--theme-text-color: #333;
		/* 默认主题色 */
		--theme-box-bg: #fff;
		/* 默认主题色 */
		--theme-input-bg: #ddd;
		/* 默认主题色 */
		--theme-pupop-bg: #fff;
		/* 默认主题色 */
		--theme-btn-pr: #1a1a1a;
		/* 默认主题色 */
	}

	page {
		background-color: var(--theme-color);
		/* padding: 0.625rem; */
		font-family: PingFang SC, PingFang SC;
		color: var(--theme-text-color);
		box-sizing: border-box;
		font-size: 16px;
	}

	.uni-page-head {
		background-color: var(--theme-color) !important;
		color: var(--theme-text-color) !important;
		border-bottom: 1px solid var(--theme-input-bg);
	}

	.uni-page-head-btn {
		color: var(--theme-text-color) !important;
	}

	.uni-page-head-btn svg {
		fill: var(--theme-text-color) !important;
		stroke: var(--theme-text-color) !important;
		/* 同时修改 stroke 属性 */
	}

	.uni-tabbar-bottom .uni-tabbar {
		background-color: var(--theme-color) !important;
	}

	::v-deep .uni-tabbar__item .uni-tabbar__label {
		font-size: 16px !important;
		color: var(--theme-text-color) !important;
		font-weight: bold !important;
		opacity: 0.6;
	}

	/*每个页面公共css */
	.flex {
		display: flex;
		align-items: center;
	}

	.flex-wrap {
		flex-wrap: wrap;
	}

	.flex-center {
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.flex-between {
		display: flex;
		align-items: center;
		justify-content: space-between;
	}

	.flex-column {
		display: flex;
		flex-direction: column;
		align-items: center;
	}

	.p10 {
		padding: 20rpx;
	}

	.pl5 {
		padding-left: 10rpx;
	}

	.pl10 {
		padding-left: 20rpx;
	}

	.p-lr-28 {
		padding: 0 56rpx;
	}

	.p-lr-16 {
		padding: 0 32rpx;
	}

	.mt5 {
		margin-top: 10rpx;
	}

	.mt10 {
		margin-top: 20rpx;
	}

	.mt15 {
		margin-top: 30rpx;
	}

	.mt20 {
		margin-top: 40rpx;
	}

	.mt30 {
		margin-top: 60rpx;
	}

	.mt50 {
		margin-top: 100rpx;
	}

	.fs20 {
		font-size: 40rpx;
	}

	.fs10 {
		font-size: 20rpx;
	}

	.fs14 {
		font-size: 28rpx;
	}

	.fs16 {
		font-size: 32rpx;
	}

	.fb {
		font-weight: bold;
		color: var(--theme-text-color);
	}

	.uni-input-placeholder {
		color: #c9c9c9 !important;
	}

	.u-button--info {
		color: #323233;
		background-color: #fff;
		border-color: #ebedf0;
		border-width: 1px;
		border-style: solid;
	}

	.u-button--normal {
		padding: 0 12px;
		font-size: 14px;
	}

	.highlight-color {
		color: #1a7acb;
	}

	.text-des-color {
		color: #999;
	}

	.btn-submit {
		height: 46px;
		border: none !important;
		text-align: center;
		font-size: 16px;
	}

	.login-btn-disabled {
		background-color: #ebeff1 !important;
		color: #a8a9ac !important;
		border: none !important;
		border-radius: 12px !important;
		line-height: 44px;
	}

	uni-button:after {
		border: none;
	}

	.text-sm,
	.fs12 {
		font-size: 28rpx;
	}

	.text-md {
		font-size: 32rpx;
	}

	.uni-easyinput {
		box-sizing: border-box;
	}

	.uni-easyinput__content-input {
		height: auto;
	}

	.login-btn {
		background-color: #1a7acb !important;
		color: #fff !important;
		border: unset !important;
		border-radius: 12px !important;
		line-height: 44px;
	}

	.text-main-color {
		color: var(--theme-text-color);
	}

	.back-btn {
		color: #fff !important;
		background-color: #cbcbcb;
	}

	.icon-xl {
		width: 38px;
		height: 38px;
	}

	.circle {
		border-radius: 50%;
	}

	.nav-h {
		height: 50px;
	}

	.u-input {
		border-radius: 12px !important;
		background-color: #fff;
		padding: 6px 7px !important;
		caret-color: #c9c9c9;
	}

	.selected {
		background-color: #f3f5f6;
	}

	.position-relative {
		position: relative;
	}

	.position-absolute {
		position: absolute;
	}

	.text-align-center {
		text-align: center;
	}

	.nav-bg {
		background-color: var(--theme-color);
	}

	.page-main {
		background-color: var(--theme-color);
	}

	.radius-12 {
		border-radius: 12px !important;
	}

	.flex-2 {
		flex: 2;
	}

	.text-row {
		display: -webkit-box;
		-webkit-box-orient: vertical;
		-webkit-line-clamp: 1;
		overflow: hidden;
		height: 2rem;
		line-height: 2rem;
	}

	.text-up {
		color: #0bb563 !important;
	}

	.animate__bounceInRight {
		-webkit-animation-name: bounceInRight;
		animation-name: bounceInRight;
	}

	.animate__animated {
		-webkit-animation-duration: 1s;
		animation-duration: 1s;
		-webkit-animation-duration: var(--animate-duration);
		animation-duration: var(--animate-duration);
		-webkit-animation-fill-mode: both;
		animation-fill-mode: both;
	}

	@keyframes bounceInRight {

		0%,
		60%,
		75%,
		90%,
		100% {
			-webkit-animation-timing-function: cubic-bezier(.215, .61, .355, 1);
			animation-timing-function: cubic-bezier(.215, .61, .355, 1);
		}

		0% {
			opacity: 0;
			-webkit-transform: translate3d(3000px, 0, 0) scaleX(3);
			transform: translate3d(3000px, 0, 0) scaleX(3);
		}

		60% {
			opacity: 1;
			-webkit-transform: translate3d(-25px, 0, 0) scaleX(1);
			transform: translate3d(-25px, 0, 0) scaleX(1);
		}

		75% {
			-webkit-transform: translate3d(10px, 0, 0) scaleX(.98);
			transform: translate3d(10px, 0, 0) scaleX(.98);
		}

		100% {
			-webkit-transform: translateZ(0);
			transform: translateZ(0);
		}
	}

	.position-fixed {
		position: fixed;
	}

	.mr5 {
		margin-right: 5px;
	}

	.mr10 {
		margin-right: 10px;
	}

	.mr15 {
		margin-right: 15px;
	}

	.mr20 {
		margin-right: 20px;
	}

	.circle {
		border-radius: 50%;
	}

	.uni-nav-bar-text {
		font-size: 18px !important;
		font-family: PingFang SC-Heavy, PingFang SC;
		font-weight: 800 !important;
	}

	.warning-color {
		color: #fc6d22;
	}

	.bg-down {
		background-color: #f33b50 !important;
	}

	.bg-up {
		background-color: #0bb563 !important;
	}

	.bg-defalut {
		background-color: #222 !important;
	}

	.text-up {
		color: #0bb563 !important;
	}

	.text-down {
		color: #f33b50 !important;
	}

	.uni-load-more__text {
		font-size: 12px !important;
	}

	.uni-forms-item__label {
		font-size: 32rpx !important;
		color: var(--theme-text-color) !important;
	}

	.uni-easyinput__placeholder-class {
		font-size: 28rpx !important;
		color: var(--theme-text-color) !important;
		opacity: 0.7;
	}

	.uni-input-placeholder,
	.uni-input-input {
		color: var(--theme-text-color) !important;
	}

	.uni-easyinput__content {
		background-color: var(--theme-box-bg) !important;
	}
</style>